<template>
	<view>
		login...
		<!-- #ifdef MP-WEIXIN -->
		<button type="primary" open-type="getUserInfo" @getuserinfo="getUserInfo">使用微信登录</button>
		<!-- #endif -->
	</view>
</template>

<script>
	var _self, pageOptions, session_key, openid;
	var sign = require('../../commons/sign.js');
	export default {
		data() {
			return {

			}
		},
		methods: {
			// #ifdef MP-WEIXIN
			//get openid
			getUserInfo: (info) => {
				info = info.mp.detail.userInfo;
				var sign = uni.getStorageSync('sign');
				console.log(sign)
				//userInfo {"nickName":"深海","gender":1,...avatarUrl":"https://7tdPvkPaJlkaLFFbLAffGVApluZdanLkDVplNlAhq1EJA/132"}
				// 与服务器交互将数据提交到服务端数据库
				uni.request({
					url: _self.apiServer + 'api/members/login',
					method: 'POST',
					header: {
						'content-type': "application/x-www-form-urlencoded"
					},
					data: {
						u_openid: openid,
						u_name: info.nickName,
						u_face: info.avatarUrl,
						sign: sign
					},
					success: res => {
						console.log(res);
						res = res.data; 
						// 登录成功 记录会员信息到本地
						
						if (res.status == 'ok') {
							uni.showToast({
								title: "登录成功"
							});
							uni.setStorageSync('SUID', res.data.u_id + '');
							uni.setStorageSync('SRAND', res.data.u_random + '');
							uni.setStorageSync('SNAME', res.data.u_name + '');
							uni.setStorageSync('SFACE', res.data.u_face + '');
							// 跳转
							if (pageOptions.backtype == 1) {
								uni.redirectTo({
									url: pageOptions.backpage
								});
							} else {
								uni.switchTab({
									url: pageOptions.backpage
								});
							}
						} else {
							uni.showToast({
								title: res.data
							});
						}
					},
					fail: (e) => {
						console.log(JSON.stringify(e));
					}
				});

			},
			// #endif
			
			getUserInfoUnionID: (info) =>{
				//加密数据
				var encryptedData = info.mp.detail.encryptedData;
				var iv            = info.mp.detail.iv;
				info              = info.mp.detail.userInfo;
				//info
				//userInfo {"nickName":"深海","gender":1,...avatarUrl":"https://7tdPvkPaJlkaLFFbLAffGVApluZdanLkDVplNlAhq1EJA/132"}
				//与服务器交互进行解密
				uni.request({
					url: _self.apiServer+'api/members/wxaes',
					method: 'POST',
					header: {'content-type' : "application/x-www-form-urlencoded"},
					data: {
						session_key   : session_key,
						encryptedData : encryptedData,
						iv            : iv
					},
					success: res => {
						/* 一、问题
						微信小程序通过wx.getUserInfo获取用户信息时，encryptedData 解密的数据中不包含unionid参数；
						
						二、解决
						如果你的小程序没有绑定微信开放平台，encryptedData 解密的数据中不包含unionid参数;
						如果开发者拥有多个移动应用、网站应用、和公众帐号（包括小程序），可通过unionid来区分用户的唯一性，因为只要是同一个微信开放平台帐号下的移动应用、网站应用和公众帐号（包括小程序），用户的unionid是唯一的。换句话说，同一用户，对同一个微信开放平台下的不同应用，unionid是相同的。
						所以unionId获取的前提是绑定微信开放平台 */
						
						//此处可以成功获取 unionId 利用 unionId 完成登录即可
					},
					fail: () => {},
					complete: () => {}
				});
			}
		},
		onLoad: function(options) {
			_self = this;
			pageOptions = options;

			// 预先签名
			sign.sign(_self.apiServer);  

			// #ifdef MP-WEIXIN
			// 调用 微信 login 获取 code
			uni.login({
				success: (res) => {
					uni.request({
						url: _self.apiServer + 'api/members/codeToSession',
						method: 'POST',
						header: {
							'content-type': "application/x-www-form-urlencoded"
						},
						data: {
							code: res.code
						},
						success: (sessions) => {
							console.log(sessions)
							// sessions.date 数据格式
							// expires_in:7200
							// openid:"oS6of0V0rdp9nY_BuvCnQUasOHYc"
							// session_key:"87sE2oDD8lc+aDJj0tB6+g=="
							// 获取 unionId
							res = JSON.parse(sessions.data.data);
							// console.log(sessions)
							session_key = res.session_key;
							openid = res.openid;
							// console.log(res.openid)
						},
					});
				}
			});
			// #endif
			
			//app 端微信登录
			// 手册位置 https://uniapp.dcloud.io/api/plugins/login?id=getuserinfo
			// #ifdef APP-PLUS
			uni.login({
				success: (res) => {
					console.log(res)
					/* {
						"authResult": {
							"access_token": "31_nRkxwKUB1KYYPYlVLRLEJTnupG8BNwSU0HiPAgtDp677Q9gpoZ6-JySGqkuGiwum1_KeJwtcdYTNSvFOP832hst4MQOEjuH-VV7f1cI8jLQ",
							"expires_in": 7200,
							"refresh_token": "31_nRkxwKUB1KYYPYlVLRLEJXcaJkjKCuOCsmNe8P5zHrT_PW__Nvjp1G3PH8NjAWz4AXaNHDztKyylf497-kyAYPYkCjsYBwOPhbajV2n1gX0",
							"openid": "oRrdQt7OmRe7u5IGh9fKyCHbmeK8",
							"scope": "snsapi_userinfo",
							"unionid": "oU5Yytz9LmLJ73ywrud7EwZA7GCE"
						},
						"errMsg": "login:ok"
					} */
					uni.getUserInfo({
						success: (info) => {
							console.log(info)
							// info 对象格式
							/* {
								"errMsg": "getUserInfo:ok",
								"rawData": "{\"openId\":\"oRrdQt7OmRe7u5IGh9fKyCHbmeK8\",\"nickName\":\"xiaojing\",\"gender\":1,\"city\":\"广州\",\"province\":\"广东\",\"country\":\"中国\",\"avatarUrl\":\"http://thirdwx.qlogo.cn/mmopen/vi_32/NYVXgHD0xiaFia0PicytS8hd2xNNvjVuD6GKzKpHMibZk8enwB6hx8tF7ZsYflSmW8oLlsEfKwB0c2rPVibqYibc66Bw/132\",\"unionId\":\"oU5Yytz9LmLJ73ywrud7EwZA7GCE\"}",
								"userInfo": {
									"openId": "oRrdQt7OmRe7u5IGh9fKyCHbmeK8",
									"nickName": "xiaojing",
									"gender": 1,
									"city": "广州",
									"province": "广东",
									"country": "中国",
									"avatarUrl": "http://thirdwx.qlogo.cn/mmopen/vi_32/NYVXgHD0xiaFia0PicytS8hd2xNNvjVuD6GKzKpHMibZk8enwB6hx8tF7ZsYflSmW8oLlsEfKwB0c2rPVibqYibc66Bw/132",
									"unionId": "oU5Yytz9LmLJ73ywrud7EwZA7GCE"
								},
								"signature": ""
							} */
							// 与服务器交互将数据提交到服务端数据库
							var sign = uni.getStorageSync('sign');
							uni.request({
							   url: _self.apiServer+'api/members/login',
								method: 'POST',
								header: {'content-type' : "application/x-www-form-urlencoded"},
								data: {
									u_openid : info.userInfo.openId,
									u_name   : info.userInfo.nickName,
									u_face   : info.userInfo.avatarUrl,
									sign :sign
								},
								success: res => {
									console.log(res.data)
									/* {
										"status": "ok",
										"data": {
											"u_openid": "oRrdQt7OmRe7u5IGh9fKyCHbmeK8",
											"u_name": "xiaojing",
											"u_face": "http://thirdwx.qlogo.cn/mmopen/vi_32/NYVXgHD0xiaFia0PicytS8hd2xNNvjVuD6GKzKpHMibZk8enwB6hx8tF7ZsYflSmW8oLlsEfKwB0c2rPVibqYibc66Bw/132",
											"u_random": "5e81aad3f05b4",
											"u_regtime": 1585556179,
											"u_id": 9 
										}
									} */
									res = res.data;
									// 登录成功 记录会员信息到本地
									if(res.status == 'ok'){
										uni.showToast({title:"登录成功"});
										
										uni.setStorageSync('SUID' , res.data.u_id + '');
										uni.setStorageSync('SRAND', res.data.u_random + '');
										uni.setStorageSync('SNAME', res.data.u_name + '');
										uni.setStorageSync('SFACE', res.data.u_face + '');
										// 跳转
										if(options.backtype == 1){
											uni.redirectTo({url:options.backpage});
										}else{
											uni.switchTab({url:options.backpage});
										}
									}else{
										uni.showToast({title:res.data});
									}
								},
								fail: (e) => {
									console.log(JSON.stringify(e));
								}
							});
						},
						fail: () => {
							uni.showToast({title:"微信登录授权失败"});
						}
					})
				},
				fail: () => {
					uni.showToast({title:"微信登录授权失败"});
					uni.hideLoading();
				}
			})
			// #endif
		}
	}
</script>

<style>

</style>
